<template>
  <el-button id="open" type="plain" circle @click="openUsart">
    {{ isUsartOpen ? '✔️' : '❌' }}
  </el-button>
  <div class="demo-progress">
    <div class="text">
      <span class="title">温度阈值</span>
      <span class="title">湿度阈值</span>
      <span class="title">浓度阈值</span>
    </div>
    <div class="charts">
      <el-progress type="dashboard" :percentage="(data[0]*100 / maxTemp).toFixed(2)" :color="colors" />
      <el-progress type="dashboard" :percentage="(data[1]*100 / maxHumi).toFixed(2)" :color="colors" />
      <el-progress type="dashboard" :percentage="(data[2]*100 /maxMq).toFixed(2)" :color="colors" />
    </div>
    <div class="btns">
      <span><input type="text" class="max-val" v-model="maxTemp"><el-button type="danger" plain @click="setMaxTemp">发送</el-button></span>
      <span><input type="text" class="max-val"  v-model="maxHumi"><el-button type="primary" plain @click="setMaxHumi">发送</el-button></span>
      <span><input type="text" class="max-val"  v-model="maxMq"><el-button type="warning" plain @click="setMaxMq">发送</el-button></span>
    </div>
  </div>
</template>

<script>
import { Howl } from 'howler'
import axios from 'axios'
import { showMsg } from '@/utils/showMsg'
import formatDateTime from '@/utils/getLocalDateTime'

export default {
  props: {
    data: {
      type: Array,
      required: true,
      default: () => [20, 20, 20]
    }
  },

  data()
  {
    return {
      maxTemp: 40,
      maxHumi: 60,
      maxMq: 60,
      soundWen: null,
      soundShi: null,
      soundMq: null,
      isUsartOpen: false,
      colors: [
        { color: '#f56c6c', percentage: 100 },
        { color: '#e6a23c', percentage: 80 },
        { color: '#5cb87a', percentage: 60 },
        { color: '#1989fa', percentage: 40 },
        { color: '#6f7ad3', percentage: 20 }
      ],
      activeSounds: [] // 跟踪当前活动的音频
    }
  },
  
  computed: {
    // 返回需要播放的所有音频
    soundsToPlay()
    {
      const sounds = []
      if (this.data[0] >= this.maxTemp) sounds.push('soundWen')
      if (this.data[1] >= this.maxHumi) sounds.push('soundShi')
      if (this.data[2] >= this.maxMq) sounds.push('soundMq')
      return sounds
    }
  },
  
  watch: {
    // 监听需要播放的音频变化
    soundsToPlay(newSounds, oldSounds)
    {
      // 停止不再需要的音频
      oldSounds.forEach(sound =>
      {
        if (!newSounds.includes(sound) && this[sound])
          this[sound].stop()
      })
      
      // 播放新需要的音频
      newSounds.forEach(sound =>
      {
        if (!oldSounds.includes(sound) && this[sound])
          this.playAudio(sound)
      })
    },

    // 监听 data 和 maxTemp、maxHumi、maxMq 的变化
    data: {
      deep: true, // 深度监听 data 数组的变化
      handler()
      {
        this.isWarning()
      }
    },
    maxTemp: {
      handler()
      {
        this.isWarning()
      }
    },
    maxHumi: {
      handler()
      {
        this.isWarning()
      }
    },
    maxMq: {
      handler()
      {
        this.isWarning()
      }
    }
  },
  
  methods: {
    setMaxTemp()
    {
      axios.post('/node/usart/send', {
        data: `@max1:${this.maxTemp}`
      })
        .then(res =>
        {
          showMsg(res.data.msg, null, 'success')
        })
        .catch(e =>
        {
          showMsg(e, null, 'warning')
        })
    },
    
    setMaxHumi()
    {
      axios.post('/node/usart/send', {
        data: `@max2:${this.maxHumi}`
      })
        .then(res =>
        {
          showMsg(res.data.msg, null, 'success')
        })
        .catch(e =>
        {
          showMsg(e, null, 'warning')
        })
    },
    
    setMaxMq()
    {
      axios.post('/node/usart/send', {
        data: `@max3:${this.maxMq}`
      })
        .then(res =>
        {
          showMsg(res.data.msg, null, 'success')
        })
        .catch(e =>
        {
          showMsg(e, null, 'warning')
        })
    },
    
    openUsart()
    {
      if (!this.isUsartOpen)
      {
        axios.post('/node/usart/init')
          .then(res =>
          {
            showMsg(res.data.msg, null, 'success')
            this.isUsartOpen = true
          })
          .catch(e =>
          {
            showMsg(e, null, 'warning')
          })
      }
      else
      
        this.isUsartOpen = false
    },
    
    playAudio(sound)
    {
      if (this[sound])
      {
        this[sound].stop() // 停止当前播放
        this[sound].seek(0) // 重置播放位置到开头
        this[sound].play() // 重新播放
      }
    },
    
    stopAudio()
    {
      [this.soundWen, this.soundShi, this.soundMq].forEach(sound =>
      {
        if (sound)
        {
          sound.stop()
          sound.seek(0) // 重置所有音频位置
        }
      })
    },

    isWarning()
    {
      if (this.data[0] >= this.maxTemp)
      {
        axios.post('/node/ar/add', {
          type: '温度过高',
          current_value: this.data[0],
          current_max: this.maxTemp,
          createdAt: formatDateTime(new Date())
        })
          .catch(e => showMsg(e, null, 'warning'))
        this.$emit('dataChange')
      }

      if (this.data[1] >= this.maxHumi)
      {
        axios.post('/node/ar/add', {
          type: '湿度过高',
          current_value: this.data[1],
          current_max: this.maxHumi,
          createdAt: formatDateTime(new Date())
        })
          .catch(e => showMsg(e, null, 'warning'))
        this.$emit('dataChange')
      }

      if (this.data[2] >= this.maxMq)
      {
        axios.post('/node/ar/add', {
          type: '浓度过高',
          current_value: this.data[2],
          current_max: this.maxMq,
          createdAt: formatDateTime(new Date())
        })
          .catch(e => showMsg(e, null, 'warning'))
        this.$emit('dataChange')
      }
    }
  },
  
  mounted()
  {
    // 初始化音频对象
    this.soundWen = new Howl({
      src: ['/sounds/wen.mp3'],
      volume: 1.0,
      onend: () => console.log('温度警报播放结束')
    })
    
    this.soundShi = new Howl({
      src: ['/sounds/shi.mp3'],
      volume: 1.0,
      onend: () => console.log('湿度警报播放结束')
    })
    
    this.soundMq = new Howl({
      src: ['/sounds/mq.mp3'],
      volume: 1.0,
      onend: () => console.log('浓度警报播放结束')
    })
  }
}
</script>

<style scoped>
.demo-progress {
  user-select: none;
  width: 760px;
  height: 200px;
}
.text {
  display: flex;
  justify-content: space-between;
  margin: 0 74px;
}
.title {
  color: #333333;
  font-weight: 600;
}
.charts {
  display: flex;
  justify-content: space-between;
  margin: 10px 60px 0 60px;
}
.btns {
  display: flex;
  justify-content: space-between;
  margin: 10px 62px 0 62px;
}

.max-val {
  width: 24px;
  margin-right: 8px;
  padding: 2px 10px;
}
.demo-progress .el-progress--line {
  margin-bottom: 15px;
  max-width: 600px;
}
.demo-progress .el-progress--circle {
  margin-right: 15px;
}
#open {
  user-select: none;
  position: absolute;
  top: 216px;
  right: 30px;
  z-index: 1;
  color: white;
}
</style>
